package com.situ.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * Feign请求拦截器，用于在微服务间的调用中传递JWT。
 * 它会自动从当前请求的上下文中获取Authorization头，并将其添加到即将发出的Feign请求中。
 */
public class FeignAuthRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        // 1. 使用RequestContextHolder获取当前请求的属性
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            // 2. 获取原始请求的Authorization头
            String token = request.getHeader("Authorization");
            // 3. 如果存在，则将其添加到Feign请求的头中
            if (StringUtils.hasText(token)) {
                template.header("Authorization", token);
            }
        }
    }
}
